<style lang="scss" scoped>

@import '../../style/mixin.scss';
.buy-cart {
    .price-icon {
        position: relative;
        top: 0.16rem;
        img {
            @include wh(0.8rem, 0.8rem);
        }
    }
}

.cart_num {
    font-size: .65rem;
    color: #666;
    min-width: 1rem;
    text-align: center;
    font-family: Helvetica Neue, Tahoma;
    display: inline-block;
}

</style>

<template lang="html">

<section class="buy-cart cart_button">
    <span class="price-icon" v-if="foodNum" @click="removeOutCart(foods.id,foods.foodName,foods.price)"><img src="../../assets/images/remove.png" alt=""></span><span class="cart_num" v-if="foodNum">{{foodNum}}</span><span class="price-icon" @click="addToCart(foods.id,foods.foodName,foods.price)"><img src="../../assets/images/add.png" alt=""></span>
</section>

</template>

<script>

import {
    mapState, mapMutations
}
from 'vuex'
export default {
    props: ['foods', 'shopId'],
    data() {
        return {
            timer: 1
        }
    },
    computed: {
        ...mapState([
                'cartList'
            ]),
            /**
             * 监听cartList变化，更新当前商铺的购物车信息shopCart，同时返回一个新的对象
             */
            shopCart: function() {
                return Object.assign({}, this.cartList[this.shopId]);
            },
            //shopCart变化的时候重新计算当前商品的数量
            foodNum: function() {
              // console.log(this.shopCart)
                    let food_id = this.foods.id;

                    if (this.shopCart&&this.shopCart[food_id]) {
                        let num = 0;
                        Object.values(this.shopCart[food_id]).forEach((item,index) => {
                            // console.log(item)
                            num += item.num;
                        })
                        return num;
                    }else {
                        return 0;
                    }
            },
    },
    created() {

    },
    mounted() {

    },
    methods: {
        ...mapMutations([
                'ADD_CART','REDUCE_CART'
            ]),
            //加入购物车，计算按钮位置。
            addToCart(food_id, food_name, food_price) {
                this.ADD_CART({
                    shopid: this.shopId,
                    food_id,
                    food_name,
                    food_price
                });
            },
            //移出购物车
            removeOutCart(food_id, food_name, food_price){
                if (this.foodNum > 0) {
                    this.REDUCE_CART({shopid: this.shopId, food_id, food_name, food_price});
                }
            },
    }
}

</script>
